#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time    : 2024/11/26 12:35
# @Author  : zmz
# @File    : net_present_value.py
# @function: 净现值
# @Software: PyCharm

import PySimpleGUI as sg
import numpy_financial as npf

import debug_infomation as _debug
import public_data as _pub

# 净现金流量布局
layout = [
    [sg.Text("折现率(小数形式输入)：")],
    [sg.InputText(key='-NPV_DISCOUNT_RATE-', default_text="0.02", size=(10, 1), readonly='true')],
    [sg.Text("方案一各期现金流量（用英文逗号分隔输入）：")],
    [sg.InputText(key='-CASH_FLOWS1-', default_text="-1000, -100, -100, -100, -100, -100", size=(130, 1))],
    [sg.Text("方案二各期现金流量（用英文逗号分隔输入）：")],
    [sg.InputText(key='-CASH_FLOWS2-', default_text="-1000, -100, -100, -100, -100, -100", size=(130, 1))],
    [sg.Text("方案三各期现金流量（用英文逗号分隔输入）：")],
    [sg.InputText(key='-CASH_FLOWS3-', default_text="-1000, -100, -100, -100, -100, -100", size=(130, 1))],
    [sg.Text("方案四各期现金流量（用英文逗号分隔输入）：")],
    [sg.InputText(key='-CASH_FLOWS4-', default_text="-1000, -100, -100, -100, -100, -100", size=(130, 1))],
    [sg.Button("计算NPV")]
]


# 标准接口实现. 每个计算都需要包含.
def update_pub_data(pub_data):
    if not pub_data:
        layout[1][0].update(_pub.pub_r)
        return
    layout[1][0].update(pub_data['PUB_R_INPUT-'])


# 标准接口实现. 每个计算都需要包含.
def update_excel_data(excel_data):
    grouped_data = excel_data.groupby('solution')

    # 定义特定顺序
    # order = ['X1Z', 'X1D']
    # 获取分组顺序（按首次出现顺序）
    order = excel_data['solution'].drop_duplicates().tolist();
    # order = ['Q1Z', 'Q1D', 'Q2Z', 'Q2D']
    # order = ['Y1Z', 'Y1D', 'Y2Z', 'Y2D']
    # 按特定顺序重新索引分组结果
    grouped_data_ordered = {key: grouped_data.get_group(key) for key in order if key in grouped_data.groups}

    index = 3
    for group_name, group_data in grouped_data_ordered.items():
        # 获取 net_cash_flow 列的数据
        net_cash_flow = group_data['et_cash_flow']

        # 将 net_cash_flow 列的数据转换为逗号分隔的字符串
        cash_flow_str = ', '.join(map(str, net_cash_flow))

        # 更新 irr_layout 中的现金流
        layout[index][0].update(value=cash_flow_str)

        index += 2;


# 净现值计算
def net_calculate_npv(discount_rate, cash_flows):
    npv = npf.npv(discount_rate, cash_flows)
    return npv


# 净现值计算处理
def Net_Present_Value_Handle(values):
    # 获取输入的现金流数据并转换为列表
    keys = ['-CASH_FLOWS1-', '-CASH_FLOWS2-', '-CASH_FLOWS3-', '-CASH_FLOWS4-']
    i = 1;
    for key in keys:
        try:
            discount_rate = float(values['-NPV_DISCOUNT_RATE-'])
            cash_flows_str = values[key]
            cash_flows = [float(x) for x in cash_flows_str.split(",")]
            npv_result = net_calculate_npv(discount_rate, cash_flows)
            temp_value = "{:.3f}".format(npv_result)
            _debug.info('方案{} 净现值（NPV）为：{}'.format(i, temp_value))
            i = i + 1
        except ValueError:
            sg.popup("输入有误，请检查输入的折现率和现金流格式是否正确。")
